/**
 * 一个类似Promise的类，但是他是可打断的
 * @author GuoHua Liu
 * @copyright Copyright © 2019 GuoHua Liu. All rights reserved.
 */
class Task {


    /**
     * 成功回调
     * @callback Resolve
     * @param {*} resp 成功时返回的数据
     */

    /**
     * 错误回调
     * @callback Reject
     * @param {*} error 错误信息
     */

    constructor() {
        this.name = ""
        this.__id = 0
        this.__isReject = false
        this.__isResolve = false
        this.__resolveResp = null
        this.__rejectResp = null
    }

    __setAbort(abort) {
        this.__abort = abort
    }

    __reject(resp) {
        if(this.__isReject ) {
            console.warn("尝试定型一个已经定型的任务")
            return
        }
        this.__rejectResp = resp
        this.__isReject = true;

        if (this.__isReject && this.__user_reject) {
            this.__user_reject(this.__rejectResp)
            return
        }
    }

    __resolve(resp) {
        if(this.__isResolve || this.__isReject ) {
            console.warn("尝试定型一个已经定型的任务")
            return
        }
        this.__resolveResp = resp
        this.__isResolve = true;

        if (this.__isResolve && this.__user_resolove) {
            this.__user_resolove(this.__resolveResp)
            return
        }
    }

    /**
     * 监听成功或者错误
     * @param {Resolve} resolove
     * @param {Reject} reject
     */
    then(resolove, reject) {
        this.__user_resolove = resolove
        this.__user_reject = reject

        // 如果已经定型，直接返回结果

        if (this.__isResolve && this.__user_resolove) {
            this.__user_resolove(this.__resolveResp)
            return
        }

        if (this.__isReject && this.__user_reject) {
            this.__user_reject(this.__rejectResp)
            return
        }
        return this;
    }

    /**
     * 监听错误
     * @param {Reject} reject
     */
    catch(reject) {
        this.__user_reject = reject
        if (this.__isReject && this.__user_reject) {
            this.__user_reject(this.__resolveResp)
        }
        return this;
    }

    /**
     * 打断任务
     */
    abort() {
        // console.log("打断任务" + this.name)
        if(this.__abort) {
            this.__abort()
            // 释放内存，避免循环引用
            this.name = undefined
            this.__id = undefined
            this.__abort = undefined
            this.__user_reject = undefined
            this.__user_resolove = undefined
            return
        }
    }
}

export {Task}
